package utils

import (
	"errors"
	"net/http"
	models "yuanaiproblem/dao/model"
	response "yuanaiproblem/models"

	"github.com/gin-gonic/gin"
)

// getCurrentUser 从上下文获取当前用户（models.User类型）
func GetCurrentUser(c *gin.Context) (models.User, error) {
	currentUser, exists := c.Get("current_user")
	if !exists {
		return models.User{}, errors.New("未登录")
	}
	return currentUser.(models.User), nil
}

// handleUserServiceError 统一处理用户服务层返回的错误
func HandleUserServiceError(c *gin.Context, err error) {
	switch err.Error() {
	case "用户不存在":
		response.Error(c, http.StatusNotFound, err.Error())
	case "用户名已存在", "无效的角色":
		response.Error(c, http.StatusBadRequest, err.Error())
	case "无权限更新他人密码", "仅管理员可更新角色":
		response.Error(c, http.StatusForbidden, err.Error())
	default:
		response.Error(c, http.StatusInternalServerError, "更新用户失败: "+err.Error())
	}
}
